﻿using System;
using StackExchange.Redis;

namespace StackExchangeRedisTest
{
    public class RedisService
    {
        #region 字符串操作
        /// <summary>
        /// 键值形式来保存字符串值。 如果键已具有值，则将其覆盖
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="value">值</param>
        /// <param name="expireSeconds">几秒后过期</param>
        /// <returns></returns>
        public bool Set(string key, string value, long expireSeconds)
        {
            key = MergeKey(key);
            var db = RedisManager.Manager.GetDatabase();

            if (expireSeconds > 0)
            {
                return db.StringSet(key, value, TimeSpan.FromSeconds(expireSeconds));
            }

            return db.StringSet(key, value);
        }

        public string Get(string key)
        {
            key = MergeKey(key);
            var db = RedisManager.Manager.GetDatabase();

            return db.StringGet(key);
        }

        public bool HasKey(string key)
        {
            key = MergeKey(key);
            var db = RedisManager.Manager.GetDatabase();

            return db.KeyExists(key);
        }
        #endregion
        #region 发布和订阅
        public void Publish(string channel, string value)
        {
            ISubscriber sub = RedisManager.Manager.GetSubscriber();
            sub.Publish(channel, value);
        }

        public void Subscribe(string redischannel, Action<string> action)
        {
            ISubscriber sub = RedisManager.Manager.GetSubscriber();
            sub.Subscribe(redischannel, (channel, message) =>
            {
                action($"{channel}:{message}");
            });

        }
        #endregion

        public int KeySecondsToLive(string key)
        {
            key = MergeKey(key);
            var db = RedisManager.Manager.GetDatabase();
            var ts = db.KeyTimeToLive(key);
            if (ts.HasValue)
            {
                return ts.Value.Seconds;
            }
            return 0;
        }

        public bool Remove(string key)
        {
            key = MergeKey(key);
            var db = RedisManager.Manager.GetDatabase();

            return db.KeyDelete(key);
        }

        private string MergeKey(string key)
        {
            return $"{key}";
        }
    }
}
